package org.apache.ocean;

import java.io.File;
import java.net.URL;
import java.util.logging.Logger;

import org.jdom.Element;

/**
 *
 * @author  jason rutherglen
 */
public class SearchConfig {
  public static Logger log = Logger.getLogger(SearchConfig.class.getName());
  public CLong searchThreadPoolSizeMax = new CLong(40);
  public CLong updateThreadPoolSizeMax = new CLong(10);
  public URL url;
  public File indicesDirectory;
  public File tempDirectory;
  public File nameURLsFile;
  public File nodeIDFile;
  public File cellIDFile;

  public static SearchConfig loadSearchConfig() throws Exception {
    File oceanHome = ClusterUtil.getOceanHome();
    File configFile = new File(oceanHome, "config.xml");
    log.info("configFile: "+configFile.getAbsolutePath());
    Element element = XMLUtil.parseElement(configFile);
    SearchConfig searchConfig = null;
    if (element != null) {
      searchConfig = (SearchConfig)ClusterUtil.construct(element, SearchConfig.class);
    } else searchConfig = new SearchConfig();
    if (searchConfig.url == null) throw new Exception("url not defined in config.xml");
    if (searchConfig.indicesDirectory == null) searchConfig.indicesDirectory = new File(oceanHome, "indices");
    searchConfig.indicesDirectory.mkdirs();
    if (searchConfig.tempDirectory == null) searchConfig.tempDirectory = new File(oceanHome, "temp");
    searchConfig.tempDirectory.mkdirs();
    if (searchConfig.nameURLsFile == null) searchConfig.nameURLsFile = new File(oceanHome, "names.txt");
    if (searchConfig.nodeIDFile == null) searchConfig.nodeIDFile = new File(oceanHome, "nodeid.txt");
    if (searchConfig.cellIDFile == null) searchConfig.cellIDFile = new File(oceanHome, "assignedcellid.txt");
    if (!searchConfig.nameURLsFile.exists()) throw new Exception(searchConfig.nameURLsFile.getAbsolutePath()+" does not exist");
    return searchConfig;
  }

  public SearchConfig() {
  }

  public SearchConfig(Element element) throws Exception {
    XMLUtil.reflectToObject(this, element);
  }
  /**
  File clusterDir = new File(homeDirectory, "webapps"+File.separatorChar+"cluster");
  Iterator iterator = FileUtils.iterateFiles(clusterDir, FileFilterUtils.nameFileFilter("searchconfig.xml"), FileFilterUtils.trueFileFilter());
  if (iterator.hasNext()) {
  File defaultSearchConfigFile = (File)iterator.next();
  FileUtils.copyFile(defaultSearchConfigFile, searchConfigFile);
  }
   */
}
